package com.woniu.hisgateway.filter;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.his.result.Result;
import com.woniu.his.sms.client.SmsPermissionClient;
import com.woniu.hisgateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @version: java version 1.8
 * @Author: ZJH
 * @description:
 * @date: 2022-12-02 10:36
 */
@Component
public class HisFilter implements GlobalFilter, Ordered {

    @Resource
    private ObjectMapper objectMapper;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //过滤请求设置
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = String.valueOf(request.getPath());
        if(path.endsWith("login")||path.endsWith("register")){
            return chain.filter(exchange);
        }
        //取token
        HttpHeaders headers = request.getHeaders();
        String his_token = headers.getFirst("his_token");
        if(his_token==null){
            return getVoidMono(response,"不存在token");
        }
        //判断空字符串
        if(StringUtils.isBlank(his_token)){
            return getVoidMono(response,"不存在token");
        }
        //解析token
        try {
            Claims claims = JwtUtil.parse(his_token);
            Object staffId = claims.get("staffId");
            Object patientId = claims.get("patientId");
            List<String> urls = (List<String>) claims.get("urls");
            request.mutate().header("staffId",staffId+"");
            request.mutate().header("patientId",patientId+"");
            if(staffId!=null) {
                for (String url : urls) {
                    if(path.endsWith(url))return chain.filter(exchange);
                }
            }
            if(patientId!=null){
                if(path.contains("app")) return chain.filter(exchange);
            }
        }catch (Exception e){
            e.printStackTrace();
            return getVoidMono(response,"token不存在或已过期");
        }
        return getVoidMono(response,"没有权限访问");
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE-10;
    }

    private Mono<Void> getVoidMono(ServerHttpResponse response,String message) throws JsonProcessingException, UnsupportedEncodingException {
        Result result = new Result();
        result.setCode(403);
        result.setMsg(message);

        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        String jsonResult = objectMapper.writeValueAsString(result);
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonResult.getBytes("UTF-8"));

        return response.writeWith(Mono.just(dataBuffer));
    }
}
